<?php

/*
    User controller controls actions related to users.
    Main functionality: authorization, language system, registration.
 */

//Social package for Facebook authorization
use Social\Facebook;

class Controller_User extends \Fuel\Core\Controller_Template {
    private $user_data;
    private $user_id;
    private $language;
    
    public function before() {
        $this->language = Cookie::get((Auth::check() ? 'user' : 'guest') . '_language', 'lv');
        Config::set("language", $this->language);
        Lang::load('main', null, $this->language, true);
        
        parent::before();
        $this->user_data = Auth::instance();
        $this->user_id = $this->user_data->get_user_id();
        
        $this->template->language = $this->language;
        $this->template->genres = Model_Orm_Genre::find('all');
        $this->template->cinema_info = Model_Orm_Cinema::find('first');
    }
    
    public function action_register() {
        if($this->user_id[1] != 0) {
            Response::redirect('/');
        }

        if(Input::method() === "POST") {
            $validation = Model_Orm_User::validate("register");
            if(     $validation->run() && Input::post("Password1") === Input::post("Password2") /*&&
                    $this->username_already_exists(Input::post("Username")) === false*/) {
                
                
                $custom_fields = array();
                $custom_fields['first_name'] = Input::post("Firstname");
                $custom_fields['last_name'] = Input::post("Lastname");
                
                try {
                    $this->user_data->create_user(Input::post("Username"), Input::post("Password1"), Input::post("Email"), 1, $custom_fields);
                } catch(Auth\SimpleUserUpdateException $e) {    //Registration failed.
                    $errors = "Neizdevās: ";
                    switch($e->getCode()) {
                        case 3: {
                            $errors .= "lietotājvārds jau ir reģistrēts ";
                        }
                        case 2: {
                            $errors .= "e-pasts jau ir reģistrēts ";
                        }
                    }
                    
                    Session::set_flash('error', $errors);
                    Response::redirect('/user/register');
                }
                    
                    $email = Email::forge();
                    $email->from('janis.zusans@gmail.com', 'Cinema IS');

                    $email->to($validation->validated("Email"), $validation->validated("First_name") . ' ' . $validation->validated("Last_name"));
                    $email->subject('Jauna lietotāja izveide');

                    $mail_text =    "Jūs esat izveidojis jaunu lietotāja kontu!" .
                                    "Lietotājs: " .  Input::post("Username") .
                                    "Parole: " . Input::post("Password1").
                                    "Adrese: http://cinemais.lv";
                    
                    $email->body($mail_text);
                    $email->send();
                
                Session::set_flash('success', 'Lietotājs izveidots !');
                Response::redirect('user/login');
                
            } else {
                Session::set_flash('error', 'Reģistrācijas kļūda');
                Response::redirect('user/register');
            }
        }
        
        $view_registration = View::forge('user/register');
        $this->template->page_content = $view_registration;
    }
    
    public function action_login() {
        if(Input::method() === "POST") {
            if ($this->user_data->login()) {
                
                if($this->user_data->get_profile_fields('blocked') == 1) {
                    Session::set_flash('error', 'Profils ir bloķēts.');
                    Auth::logout();
                    Response::redirect('/');
                } else {
                    Session::set_flash("success", "Jūs esat veiksmīgi ienācis sistēmā.");
                    Cookie::delete('user_language');

                    $user_language = $this->user_data->get_profile_fields('language');

                    if($user_language == 'lv' || $user_language == 'en') {
                        Cookie::set('user_language', $user_language, 604800); 
                    } else {
                        Cookie::set('user_language', 'lv', 604800);   
                    }

                    Response::redirect('/');   
                }
            } else {
                Session::set_flash('error', 'Kļūda ievadītajos lietotāja datos.');
                $view_login = View::forge('user/login');
                $this->template->page_content = $view_login;
            }
        } else {
            $view_login = View::forge('user/login');
            $this->template->page_content = $view_login;    
        }
    }
    
    public function action_logout() {
        if($this->user_data->check()) {
            $this->user_data->logout();
        }
        Response::redirect('/');
    }
 
/*
    //Works - sending email with FuelPHP.
    public function action_sendmail() {
	$email = Email::forge();
	$email->from('janis.zusans@gmail.com', 'Test email');

	$email->to("send-to@inbox.lv", "Hello");
	$email->subject('Subject here.');

	$mail_text = "Email text.";
	$email->body($mail_text);
	$email->send();
        
        Response::redirect('/');
    }
 */
    
    public function action_profile() {
        if($this->user_id[1] == 0) {
            Response::redirect('/');
        }
        
        $user_info = array (
            "email" => $this->user_data->get_email(),
            "firstname" => $this->user_data->get_profile_fields("firstname"),
            "lastname" => $this->user_data->get_profile_fields("lastname"),
        );
        
        $view_profile = View::forge('user/profile');
        $view_profile->set("user_info", $user_info);
        $this->template->page_content = $view_profile;   
    }
    
    public function action_changePrivateInfo() {
        if($this->user_id[1] == 0 || Input::method() !== "POST") {
            Response::redirect('/');
        }
        $validation = Model_Orm_User::validate("change_info");
        
        if($validation->run()) {
            $this->user_data->update_user(
                array(
                    "email" => Input::post("Email"),
                    "firstname" => Input::post("Firstname"),
                    "lastname" => Input::post("Lastname"),
                    "language" => "lv"
                )
            );
            Session::set_flash('success', 'Izmaiņas ir veiktas.');
            Response::redirect('/user/profile');
        } else {
            Session::set_flash('error', 'Kļūda ievadītajos datos.');
            Response::redirect('/user/profile');
        }
    }
    
    public function action_changePassword() {
        if($this->user_id[1] == 0 || Input::method() !== 'POST') {
            Response::redirect('/');
        }
        $validation = Model_Orm_User::validate('change_password');
        
        if( $validation->run() && 
            Input::post('NewPassword1') === Input::post('NewPassword2') && 
            $this->user_data->change_password(Input::post('CurrentPassword'), Input::post('NewPassword1'))) {
            
            Session::set_flash('success', 'Parole veiksmīgi nomainīta !');
            Response::redirect('/user/profile');
        } else {
            Session::set_flash('error', 'Paroli neizdevās nomainīt !');
            Response::redirect('/user/profile');
        }
    }
    
    public function action_blockProfile() {
        if($this->user_id[1] == 0 || Input::method() !== "POST") {
            Response::redirect('/');
        }
        
        $user_email = Auth::get_email();
        if( Auth::validate_user($user_email, Input::post('Password')) ) {
            $this->user_data->update_user(
                array(
                    "blocked" => "1"
                )
            );
            
            Session::set_flash('error', 'Jūsu profils ir bloķēts !');
            Auth::logout();
            Response::redirect('/');
        } else {
            Session::set_flash('error', 'Nepareiza parole !');
            Response::redirect('/user/profile'); 
        }
        
    }
    
    public function action_loginfb()
    {
	$fb = Facebook::instance();

        //Trying to log in user using Facebook authorization.
	if ($fb->check_login() == false && (time() - Session::get('time')) > 5 /* against infinite loops */) {
            
            Session::set('time', time());

	    $facebook_params = array("scope" => "email");
	    $login_url = $fb->getLoginUrl($facebook_params);
	    Response::redirect($login_url) and die();
	} else {
            //Creating new user using Facebook info.
            
            $user_profile = $fb->api('/me');
            $fb_mail = $user_profile['email'];
            $fb_id = $user_profile['id'];

            $auth = Auth::instance();

            $username = explode('@', $fb_mail);
            
            $fb_sql_user = DB::select("id")
                    ->from("users")
                    ->where("username", "=", $username[0])
                    ->execute()
                    ->as_array();

            //User doesn't exist in DB
            if (count($fb_sql_user) == 0) {		
                $user_id = $auth->create_user($username[0], hash("sha256", mt_rand(0, mt_getrandmax())), $fb_mail, 1, array(
                    "facebook_id" => $fb_id,
                    "language" => "lv")
                );
                
                $email = Email::forge();
                $email->from('janis.zusans@gmail.com', 'Cinema IS');

                $email->to($validation->validated("Email"), $validation->validated("First_name") . ' ' . $validation->validated("Last_name"));
                $email->subject('Jauna lietotāja izveide');

                $mail_text =    "Jūs esat izveidojis jaunu lietotāja kontu, izmantojot Facebook.com!" .
                                "Lietotājs: " .  Input::post("Username") .
                                "Parole: " . Input::post("Password1").
                                "Adrese: http://cinemais.lv";

                $email->body($mail_text);
                $email->send();
            } else {
                $user_id = $fb_sql_user[0]["id"];
            }

            $auth->force_login($user_id);
            
            $user_language = $this->user_data->get_profile_fields('language');

            if($user_language == 'lv' || $user_language == 'en') {
                Cookie::set('user_language', $user_language, 604800); 
            } else {
                Cookie::set('user_language', 'lv', 604800);   
            }
            
            Response::redirect("/");
	}
    }
    
    //Collects info about user's orders
    public function action_myorders() {
        if(Auth::check()) {
            $orders_info = Model_Orm_Order::query()->where('user_id', '=', $this->user_id[1])->get();
            
            $view_myorders = View::forge('user/myorders');
            $view_myorders->set("orders_info", $orders_info);
            $this->template->page_content = $view_myorders;  
        } else {
            Response::redirect('/');
        }
    }
    
    //Sets users langauge, works for registered users and guests.
    public function action_setlanguage($language = null) {
        is_null($language) and Response::redirect('/');
        
        if($language == 'lv' || $language == 'en') {
            Cookie::delete('user_language');
            
            if(Auth::check()) {
                Auth::update_user(
                    array(
                        'language' => $language
                    )
                );
                Cookie::set('user_language', $language, 604800);
                
            } else {
                Cookie::set('guest_language', $language, 604800);
            }
        }
        
        Response::redirect('/');
    }
}

?>
